package com.example.leero.graduation.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.leero.graduation.API;
import com.example.leero.graduation.App;
import com.example.leero.graduation.R;
import com.example.leero.graduation.Util.DisplayUtil;
import com.example.leero.graduation.Util.GsonUtil;
import com.example.leero.graduation.Util.ImageLoader;
import com.example.leero.graduation.Util.StringUtil;
import com.example.leero.graduation.adapter.ActDetailAdapter;
import com.example.leero.graduation.customView.SpaceItemDecoration;
import com.example.leero.graduation.model.ActivityDetail;
import com.example.leero.graduation.model.Comment;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;

import static com.example.leero.graduation.Util.DateUtil.getDateStringFromTZ2MDT;

/**
 * Created by Leero on 2017-4-22.
 */

public class DetailActivity extends AppCompatActivity {

    private SwipeRefreshLayout refresh_layout;
    private RecyclerView commentRecycleView;
    private List<Comment> dataList = new ArrayList<>();
    private HeaderAndFooterWrapper headerWrapper;
    private ActivityDetail activityDetail;
    private ActDetailAdapter adapter;
    private int act_id;
    private Boolean isNew = false;

    // headView
    private ImageView iv_avatar;
    private ImageView iv_sex;
    private ImageView iv_active_status;
    private TextView tv_nickname;
    private TextView tv_title;
    private TextView tv_sport_name;
    private TextView tv_date;
    private TextView tv_address;
    private TextView tv_comment_count;
    private TextView tv_limit;
    private TextView tv_number;

    // foot
    private TextView tv_apply;
    private TextView tv_manage;
    private Button btn_comment;
    private Boolean isApply = false;  // 报名标识，false未报名，true已报名
    private Boolean isAdmin = false;  // 活动管理员标识

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        tv_apply = (TextView) findViewById(R.id.tv_apply);
        tv_manage = (TextView) findViewById(R.id.tv_manage);
        btn_comment = (Button) findViewById(R.id.btn_comment);
        setupRv();

        Intent intent = getIntent();
        act_id = intent.getIntExtra("id", 0);
        isNew = intent.getBooleanExtra("isNew", false);
        getActivityDetail(act_id + "");

        TextView title = (TextView) findViewById(R.id.tv_title);
        title.setText("活动详情");
        findViewById(R.id.iv_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isNew) {
                    Intent intent = new Intent(DetailActivity.this, HomeActivity.class);
                    startActivity(intent);
                } else {
                    finish();
                }
            }
        });

        // 报名申请或取消报名
        tv_apply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isApply) {
                    postActCancel();
                } else {
                    postApplyAct();
                }
            }
        });
        // 活动管理
        tv_manage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdmin) {
                    Intent intent = new Intent(DetailActivity.this, ManageActivity.class);
                    intent.putExtra("act_id", act_id);
                    startActivity(intent);
                }
            }
        });
        // 评论
        btn_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2Comment = new Intent(DetailActivity.this, CommentActivity.class);
                intent2Comment.putExtra("act_id", act_id);
                startActivityForResult(intent2Comment, 1);
            }
        });

        refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getActivityDetail(act_id + "");
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isAdmin) {
            tv_apply.setVisibility(View.GONE);
            tv_manage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 1) {
            refresh_layout.setRefreshing(true);
            getActivityDetail(act_id + "");
        }
    }

    private void setupRv() {
        refresh_layout = (SwipeRefreshLayout) findViewById(R.id.refresh_layout);
        commentRecycleView = (RecyclerView) findViewById(R.id.comment_list);
        commentRecycleView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ActDetailAdapter(this, R.layout.item_comment, dataList);
        View v = LayoutInflater.from(this)
                .inflate(R.layout.view_sport_detail_head, commentRecycleView, false);
        initHeader(v);
        headerWrapper = new HeaderAndFooterWrapper(adapter);
        headerWrapper.addHeaderView(v);
        commentRecycleView.setAdapter(headerWrapper);
        commentRecycleView.addItemDecoration(new SpaceItemDecoration(DisplayUtil.dp2px(this, 3), false, true));
    }

    private void initHeader(View view) {
        iv_avatar = (ImageView) view.findViewById(R.id.iv_avatar);
        iv_sex = (ImageView) view.findViewById(R.id.iv_sex);
        iv_active_status = (ImageView) view.findViewById(R.id.iv_active_status);
        tv_nickname = (TextView) view.findViewById(R.id.tv_nickname);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_sport_name = (TextView) view.findViewById(R.id.tv_sport_type);
        tv_date = (TextView) view.findViewById(R.id.tv_date);
        tv_address = (TextView) view.findViewById(R.id.tv_address);
        tv_comment_count = (TextView) view.findViewById(R.id.tv_comment_count);
        tv_limit = (TextView) view.findViewById(R.id.tv_limit);
        tv_number = (TextView) view.findViewById(R.id.tv_number);

//        view.findViewById(R.id.rl_member).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
    }

    private void getActivityDetail(String id) {
        OkHttpUtils.post().url(API.GET_ACTIVITY_DETAIL)
                .addParams("user_id", App.getLoginUser().id + "")
                .addParams("activity_id", id).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }
            @Override
            public void onResponse(String response, int id) {
                activityDetail = GsonUtil.fromJson(response, ActivityDetail.class);
                dataList.clear();
                dataList.addAll(Arrays.asList(activityDetail.comment));
                handleHeaderView();

                if (activityDetail.publisher_id == App.getLoginUser().id) {
                    isAdmin = true;
                    tv_apply.setVisibility(View.GONE);
                    tv_manage.setVisibility(View.VISIBLE);
                }

                headerWrapper.notifyDataSetChanged();
            }

            @Override
            public void onAfter(int id) {
                refresh_layout.setRefreshing(false);
            }
        });
    }

    private void handleHeaderView() {
        if (!StringUtil.isEmpty(activityDetail.avatar)) {
            ImageLoader.load(this, iv_avatar, activityDetail.avatar);
        } else {
            iv_avatar.setImageResource(R.drawable.default_avatar_cricle);
        }

        // 0:女  1:男
        if (activityDetail.sex == 0) {
            iv_sex.setImageResource(R.drawable.draw_women);
        } else {
            iv_sex.setImageResource(R.drawable.draw_man);
        }

        if(activityDetail.is_apply == 1) {
            iv_active_status.setImageResource(R.drawable.img_active_apply);
            tv_apply.setText("取消");
            isApply = true;
        } else if (activityDetail.is_apply == 2) {
            iv_active_status.setImageResource(R.drawable.img_active_join);
            tv_apply.setText("取消");
            isApply = true;
        } else if (activityDetail.is_apply == 3) {
            iv_active_status.setImageResource(R.drawable.img_status_cancel);
        }

        tv_nickname.setText(activityDetail.user_name);
        tv_title.setText(activityDetail.title);
        tv_sport_name.setText(sportTypeToString(activityDetail.sport_type));
        tv_date.setText(getDateStringFromTZ2MDT(activityDetail.start_time)+" ~ "+getDateStringFromTZ2MDT(activityDetail.end_time));
        tv_address.setText(activityDetail.address);
        tv_limit.setText(getLimitString(activityDetail.limit_sex, activityDetail.limit_number));
        tv_comment_count.setText("" + dataList.size() + " 条评论");
        tv_number.setText(activityDetail.apply_count + "人");
    }

    private String sportTypeToString(int sportType) {
        String result = "";
        switch (sportType) {
            case 1:
                result = "跑步";
                break;
            case 2:
                result = "羽毛球";
                break;
            case 3:
                result = "乒乓球";
                break;
            case 4:
                result = "篮球";
                break;
            case 5:
                result = "足球";
                break;
            case 6:
                result = "网球";
                break;
        }
        return "（" + result + "）";
    }

    /**
     * 报名活动
     */
    private void postApplyAct() {
        OkHttpUtils.post().url(API.JOIN_ACTIVITY)
                .addParams("act_id", act_id + "")
                .addParams("user_id", App.getLoginUser().id + "")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }
            @Override
            public void onResponse(String response, int id) {
                isApply = true;
                iv_active_status.setImageResource(R.drawable.img_active_apply);
                tv_apply.setText("取消");
            }
        });
    }

    /**
     * 取消报名
     */
    private void postActCancel() {
        OkHttpUtils.post().url(API.CANCEL_REGISTRATION)
                .addParams("act_id", act_id + "")
                .addParams("user_id", App.getLoginUser().id + "")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }
            @Override
            public void onResponse(String response, int id) {
                isApply = false;
                iv_active_status.setImageResource(R.drawable.img_status_cancel);
                tv_apply.setText("报名");
            }
        });
    }

    private String getLimitString(int limit_sex, int limit_number){
        String result = "";
        if(limit_sex == 0) {
            result += "性别不限,";
        } else if(limit_sex == 1) {
            result += "只限男生,";
        } else if(limit_sex == 2) {
            result += "只限女生,";
        }

        if(limit_number == 0) {
            result += "人数不限";
        } else {
            result += "人数限制" + limit_number + "人";
        }

        return result;
    }
}
